﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.Win32;

namespace TFhisto.UI
{
    /// <summary>
    /// Interaction logic for TFSUserControl.xaml
    /// </summary>
    public partial class TFSUserControl : UserControl, INotifyPropertyChanged
    {
        private ProjectInfo[] teamProjects;
        public ProjectInfo[] TeamProjects
        {
            get
            {
                return teamProjects;
            }
            set
            {
                teamProjects = value;
            }
        }

        public string SelectedTeamProjectCollection
        {
            set
            {
                foreach (RegisteredProjectCollection item in cboServer.Items)
                {
                    if (item.Name.Equals(value))
                    {
                        cboServer.SelectedItem = item;
                        cboServer.BringIntoView();
                        break;
                    }
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        
        public TFSUserControl()
        {
            InitializeComponent();
            LoadRegisteredServers();
        }

        #region Load the registered servers on a background thread
        /// <summary>
        /// Sets the background worker thread and starts it
        /// </summary>
        public void LoadRegisteredServers()
        {
            BackgroundWorker backgroundWorker;

            backgroundWorker = new BackgroundWorker();
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_background_RunWorkerCompleted);
            backgroundWorker.DoWork += new DoWorkEventHandler(_background_DoWork);
            backgroundWorker.RunWorkerAsync();
        }

        /// <summary>
        /// Performs the actual long running work
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _background_DoWork(object sender, DoWorkEventArgs e)
        {
            RegisteredProjectCollection[] collections = RegisteredTfsConnections.GetProjectCollections();
            e.Result = collections;
        }

        /// <summary>
        /// When the work is completed, this event is raised and then the
        /// combobox is loaded and enabled
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _background_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            cboServer.ItemsSource = (RegisteredProjectCollection[])e.Result;
            cboServer.DisplayMemberPath = "Uri";
            cboServer.IsEnabled = true;
        }
        #endregion

        #region Handle server issues like connecting and loading projects
        /// <summary>
        /// Connects to the Project Collection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cboServer.Text != string.Empty)
                {
                    Mouse.OverrideCursor = Cursors.Wait;

                    CommonUIHelper.Helper._tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(cboServer.Text), new UICredentialsProvider());
                    CommonUIHelper.Helper._tfs.EnsureAuthenticated();
                    LoadProjects();
                    CommonUIHelper.Helper._wis = CommonUIHelper.Helper._tfs.GetService<WorkItemStore>();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Mouse.OverrideCursor = null;
            }
        }

        /// <summary>
        /// Loads the list of projects and enables the project combo box
        /// </summary>
        private void LoadProjects()
        {
            //Get the list of projects and display them
            CommonUIHelper.Helper._css = (ICommonStructureService)CommonUIHelper.Helper._tfs.GetService(typeof(ICommonStructureService));
            teamProjects = CommonUIHelper.Helper._css.ListProjects();

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("TeamProjects"));
            }
        }

        /// <summary>
        /// Adds a new Server/Project Collection to the list of registered servers on the
        /// local machine and then re-binds the combobox to the list of registered servers
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.NoProject, false);
            tpp.ShowDialog();
            LoadRegisteredServers();
        }
        #endregion
    }
}
